<?php

namespace app\models\money;

use app\components\Fun;
use Yii;

/**
 * This is the model class for table "{{%money_balance}}".
 * 用于余额记录表
 *
 * @property int $id
 * @property int|null $uid 用户uid
 * @property int|null $money 用户余额,单位是分,100表示1元;1表示1分
 * @property int|null $time 创建时间
 */
class MoneyBalance extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%money_balance}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['uid', 'money', 'time'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => 'Uid',
            'money' => 'Money',
            'time' => 'Time',
        ];
    }



    /**
     * 为用户充值,并返回充值日志
    */
    public static function chongzhi($money,$uid){
        $one=self::find()->where([
            'uid'=>$uid
        ])->one();
        if(!$one){
            $one=new self;
            $one->uid=$uid;
            $one->money=0;
        }
        $one->time=time();
        $log=Fun::date(time())."\t旧余额:".$one->money."\t";
        $one->money+=$money;
        $log.=Fun::date(time())."\t新余额:".$one->money."\t"."增加了:".$money;
        if($one->save()){
            return $log;
        }else{
            return false;
        }
    }

    /**
     * 返回当前用户的余额
    */
    public static function getUserMoney($uid){
        $one=self::find()->where([
            'uid'=>$uid
        ])->one();
        if(!$one){
            $one=new self;
            $one->uid=$uid;
            $one->money=0;
            $one->time=time();
            $one->save();
        }
        return $one->money/100;
    }


}
